﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace etdc
{
    internal class Ts1
    {
        private readonly byte[] _data;
        public byte[] GetBodyData()
        {
            return _data.Skip(Const.TS1_SIGNATURE_BYTES.Length).ToArray();
        }

        private void CheckSignature()
        {
            if (!_data.Take(Const.TS1_SIGNATURE_BYTES.Length).SequenceEqual(Const.TS1_SIGNATURE_BYTES))
                throw new Exception("wrong signature");
        }

        private Ts1(byte[] data)
        {
            _data = data;
            CheckSignature();
        }

        public byte[] Decrypt(IList<byte> key)
        {
            return _data.Skip(Const.TS1_SIGNATURE_BYTES.Length).XorWith(KeyGenerator.Generate(key));
        }

        public void Save(string file)
        {
            File.WriteAllBytes(file, _data);
        }

        public static Ts1 Load(string file)
        {
            return new Ts1(File.ReadAllBytes(file));
        }

        public static Ts1 Encrypt(IEnumerable<byte> source, IList<byte> key)
        {
            return new Ts1(Const.TS1_SIGNATURE_BYTES.Concat(source.XorWith(KeyGenerator.Generate(key))).ToArray());
        }
    }
}
